package com.dongdongshop.service.imp;

import com.alibaba.dubbo.config.annotation.Service;
import com.dongdongshop.pojo.comment.Comment;
import com.dongdongshop.service.CommentServiceI;
import com.dongdongshop.util.PageInfo;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
@Service
public class CommentServiceImpl implements CommentServiceI {
    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public void insertEvluateReply(String id, String reply) {
        Query query  = new Query(Criteria.where("_id").is(id));
        Update update = new Update();
        update.set("parentId",reply);
        mongoTemplate.updateFirst(query, update, Comment.class);

    }

    //更新点赞
    @Override
    public void updateLikeNum(String id) {
        //查询对象 根据id查询
        Query query = Query.query(Criteria.where("_id").is(id));
        //更新对象
        Update update=new Update();
        //更新部分字段，相当于$set
        //递增$inc update.inc("likeNum");
        update.inc("likeNum",1);
        System.out.println("点赞成功"+update);
        //参数1：查询对象 参数2：更新对象 参数3：集合的名字或实体类的类型Comment.class
        mongoTemplate.updateFirst(query,update,Comment.class);
    }

    @Override
    public PageInfo<Comment> getCommentByGoodsId(Long goodsId, Integer pageNumber, Integer pageSize) {
        PageInfo<Comment> pageInfo = new PageInfo<>();
        pageInfo.setPageNumber(pageNumber);
        pageInfo.setPageSize(pageSize);
        Query query = new Query(Criteria.where("goodId").is(goodsId));
        Long count = mongoTemplate.count(query,Comment.class);
        pageInfo.setTotal(count);
        query.skip(pageInfo.getOffset()).limit(pageInfo.getPageSize());
        List<Comment> commentList = mongoTemplate.find(query, Comment.class);
        // System.out.println("size"+commentList.size());
        pageInfo.setList(commentList);
        return pageInfo;
    }

    @Override
    public void addComment(Comment comment) {
        mongoTemplate.insert(comment);
        System.out.println("添砖："+comment);
    }
}
